import service.ReadWriteRunable;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

public class ReadRunable extends ReadWriteRunable {
    private SocketChannel socketChannel;
    private SelectionKey selectionKey;

    public ReadRunable(SocketChannel channel, SelectionKey selectionKey) {
        super(SelectionKey.OP_READ, channel);
        this.socketChannel = channel;
        this.selectionKey = selectionKey;
    }

    private ReadRunableInterface readRunableInterface;

    @Override
    public void run() {
        final int read;
        if (!selectionKey.isValid())
            return;
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
        try {
            if (socketChannel.isOpen()) {
                ByteBuffer byteBuffer = ByteBuffer.allocate(512);
                read = socketChannel.read(byteBuffer);
                if (read > 0) {
                    byteBuffer.flip();
                    String s = new String(byteBuffer.array());
                    if (s != null) {
                        s = s.trim();
                        if (s.length() > 0) {
                            System.out.println(socketChannel.getRemoteAddress() + ":" + s);
                            ByteBuffer writeBuffer = ByteBuffer.wrap(s.getBytes());
                            writeBuffer.flip();
                            this.socketChannel.write(writeBuffer);
                        }
                    }
                }
                if (read == -1) {
                    selectionKey.cancel();
                    while (selectionKey.isValid()){
                        Thread.sleep(1000);
                    }
//                    socketChannel.close();
                    if (!selectionKey.isValid())
                        System.out.println(socketChannel.socket().getRemoteSocketAddress().toString() + "：正常下线");
                }
            }
        } catch (AsynchronousCloseException exception) {
//            exception.printStackTrace();
//            System.out.println(socketChannel.socket().getRemoteSocketAddress().toString() + "：异常--强行下线");
        } catch (IOException e) {
//            e.printStackTrace();
//            System.out.println(socketChannel.socket().getRemoteSocketAddress().toString() + "：异常--正常下线");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    interface ReadRunableInterface {
        void SocketConnectorClose(SocketChannel channel);
    }
}
